using System;
using System.Collections.Generic;
using System.Linq;
using UMC.Web;
using UMC.Data.Entities;
using UMC.Proxy.Entities;
using System.IO;
using UMC.Data;
using System.Text.RegularExpressions;
using UMC.Web.UI;

namespace UMC.Proxy.Activities
{
    [UMC.Web.Mapping("Proxy", "UI", Auth = WebAuthType.User)]
    public class SiteUIActivity : UMC.Web.WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var surl = new Uri(request.Url, "/css/images/BgSrc/bg5.jpg?umc-image=m350x200o").AbsoluteUri;
            var ui = UISection.Create(new UITitle("我的应用"));

            var list = new List<WebMeta>();


            ui.Title.Banner("轻应用", "System", "Search", "Hot");
            ui.Title.Name("icon", "\uea0e");


            ui.Title.Right(new UIEventText().Icon('\uf2e1').Click(UIClick.Scanning()));

            ui.UIHeader = new UIHeader().Slider(new WebMeta[] { new WebMeta().Put("src", surl) });
            UMC.Web.UI.UIIcon iIcon = new Web.UI.UIIcon();
            if (request.IsMaster)
            {
                iIcon.Add(new UIEventText("应用管理").Icon('\uf085', 0x40c9c6).Click(new UIClick().Post("Proxy", "Site")));
                iIcon.Add(new UIEventText("组织账户").Icon('\uf0c0', 0x36a3f7).Click(new UIClick().Post("Settings", "Organize")));
                iIcon.Add(new UIEventText("功能授权").Icon('\uf214', 0x34bfa3).Click(new UIClick().Post("Settings", "AuthKey")));

                if (Host.HttpBridgeClient.IsRunning)
                {
                    // ui.Title.Right('\uf1cc',new UIClick("Http", "Bridge","Start"));
                    iIcon.Add(new UIEventText("Web VPN").Icon('\uf1cc', 0x09bb07).Click(new UIClick("Http", "Bridge", "Start")));
                }
                ui.Add(iIcon);
            }
            var home = request.Url.Authority;//

            // var union = Data.WebResource.Instance().Provider["union"] ?? ".";
            // if (Regex.IsMatch(request.Url.Host, @"^(\d{1,3}.)+\d{1,3}$"))
            // {
            //     home = UMC.Data.WebResource.Instance().WebDomain();
            //     if (home == "localhost")
            //     {
            //         union = ".";
            //     }
            // }
            var appIcons = new Web.UI.UIIcon();
            var appUI = ui.NewSection();
            appUI.Header.Put("text", "我的桌面");

            var keys = new List<String>();
            var user = this.Context.Token.Identity();

            UMC.Data.Session<UMC.Web.WebMeta> session = new Data.Session<WebMeta>($"{user.Id}_Desktop");

            var desktop = session.Value ?? new WebMeta();
            var sites = DataFactory.Instance().Site().Where(r => r.Flag != -1).Where(r => (r.IsModule ?? false) == false)
            .OrderBy((arg) => arg.Caption).ToList();

            Utility.Each(sites, r => keys.Add($"Desktop/{r.Root}"));
            var auths = UMC.Security.AuthManager.IsAuthorization(user, 0, keys.ToArray());

            var webr = UMC.Data.WebResource.Instance();
            var ds = sites.ToArray();
            for (var i = 0; i < ds.Length; i++)
            {
                var d = ds[i];

                if (auths[i])
                {
                    var strUrl = $"{request.Url.Scheme}://{d.Root}.{home}/UMC.For/{request.Server}";

                    var title = d.Caption ?? ""; ;

                    if ((d.OpenModel ?? 0) == 3)
                    {
                        strUrl = new Uri(new Uri(SiteConfig.Config(d.Domain)[0]), d.Home ?? "/").AbsoluteUri;
                    }
                    else if (SiteConfig.Config(d.AuthConf).Contains("*") || d.AuthType == WebAuthType.All)
                    {
                        strUrl = $"{request.Url.Scheme}://{d.Root}.{home}{d.Home}";
                    }
                    var isDesktop = desktop.ContainsKey(d.Root);
                    if (d.IsDesktop == true)
                    {
                        if (String.Equals("hide", desktop[d.Root]))
                        {
                            isDesktop = false;
                        }
                        else
                        {
                            isDesktop = true;
                        }

                    }
                    if (isDesktop)
                    {
                        appIcons.Add(new UIEventText(title.Trim()).Click(UIClick.Url(strUrl)).Src(webr.ImageResolve(d.Root, "1", 4, $"_t={d.ModifyTime}")));

                    }
                }
            }
            if (appIcons.Count > 0)
            {
                appUI.Add(appIcons);
            }
            else
            {
                UIDesc desc = new UIDesc("未有发布的应用");
                desc.Desc("{icon}\n{desc}").Put("icon", "\uf24a");
                desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));
                appUI.Add(desc);

            }
            // appUI.DisableSeparatorLine();
            ui.SendTo(this.Context, true, $"{request.Model}.{request.Command}");

        }

    }
}